package com.jc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author: HJC
 * @Date: 2025/11/3 19:38
 * @Description:
 **/
public class PostgreSQLDDL {

    public static void main(String[] args) {
        String url = null;
        String user = null;
        String password = null;

        // 修正SQL语句（添加字段间的逗号）
        String sql_str = "create table users (" +
                "id serial primary key," +
                "name character(10) not null unique," +
                "created_at timestamp default current_timestamp not null" +
                ")";

        // 读取数据库连接配置文件（仅类路径加载）
        try {
            InputStream is = PostgreSQLDDL.class.getResourceAsStream("/db.properties");
            if (is == null) {
                System.out.println("db.properties 未在类路径中找到");
                return;
            }
            Properties pros = new Properties();
            pros.load(is);
            url = pros.getProperty("url");
            user = pros.getProperty("user");
            password = pros.getProperty("password");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return;
        }

        // 建立数据库连接并执行建表语句
        try {
            // 显式加载PostgreSQL驱动（可选，高版本JDK可省略，但加上更稳妥）
            Class.forName("org.postgresql.Driver");
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement ps = conn.createStatement();
            ps.execute(sql_str);
            System.out.println("创建表成功!");

            // 关闭资源（好习惯）
            ps.close();
            conn.close();
        } catch (Exception e) {
            System.out.println("创建表失败：" + e.getMessage());
        }
    }
}
